<?php
/**
 * @todo A master class for navigation like zend_navigation
 */
class Menu extends CWidget {
	public $items = array ();
	protected $_navigation = array ();
	
	protected static $_module;
	protected static $_controller;
	protected static $_action;
	
	public function init() {
		parent::init ();
		$this->_navigation = Yii::app ()->dbConfig->navigation;
		$this->_initNavigationArray ();
	}
	
	public function run() {
		$this->render ( 'mainMenu', array ('navigation' => $this->_navigation ) );
	}
	
	/**
	 * @see CWebApplication::createController()
	 */
	protected function _initNavigationArray() {
		if (! empty ( $this->_navigation ) && is_array ( $this->_navigation )) {
			$app = Yii::app ();
			$route = $app->getUrlManager ()->parseUrl ( Yii::app ()->getRequest () );
			$route .= '/';
			$i = 0;
			while ( ($pos = strpos ( $route, '/' )) !== false ) {
				$id = substr ( $route, 0, $pos );
				$route = ( string ) substr ( $route, $pos + 1 );
				switch ($i) {
					case 1 :
						$controller = $id;
						break;
					case 2 :
						$action = $id;
						break;
					case 0 :
						$module = $id;
						break;
					default :
						break;
				}
				++ $i;
			}			
			/**
			 * @todo outsourcing!
			 */
			$activeCheckString = ucfirst ( $module ) . ucfirst ( $controller ) . ucfirst ( $action );
			foreach ( $this->_navigation as $key => $nav ) {
				$allowedForKey = 0;
				foreach ( $nav ['pages'] as $pageKey => $page ) {
					$pageModule = $page ['module'];
					$pageController = $page ['controller'];
					$pageAction = $page ['action'];
					/**
					 * @todo outsourcing!
					 */
					$pageCheckString = ucfirst ( $pageModule ) . ucfirst ( $pageController ) . ucfirst ( $pageAction );
					if (Yii::app ()->user->checkAccess ( $pageCheckString )) {
						++ $allowedForKey;
						$this->_navigation [$key] ['pages'] [$pageKey] ['allowed'] = true;
					} else {
						$this->_navigation [$key] ['pages'] [$pageKey] ['allowed'] = false;
					}
					if ($pageCheckString === $activeCheckString && $this->_navigation [$key] ['pages'] [$pageKey] ['allowed']) {
						$this->_navigation [$key] ['pages'] [$pageKey] ['active'] = true;
						$this->_navigation [$key] ['active'] = true;
					}
				}
				//we dont check in the template if the navi path is allowed
				if (0 === $allowedForKey) {
					$this->_navigation [$key] ['pages'] = null;
				}
			}
		} elseif (! is_array ( $this->_navigation )) {
			throw new CException ( '$this->_navigation must be set as an array' );
		}
	}
}